package org.example;

import cn.hutool.core.date.StopWatch;
import com.alibaba.excel.EasyExcel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Validator;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api")
public class HelloController {

    static class OOMObject {
    }

    @Autowired
    RestTemplate restTemplate;

    List<OOMObject> list = new ArrayList<>();

    int count;

    @GetMapping("/oom")
    public String oom() throws InterruptedException {

        System.out.println(Thread.currentThread().getName() + " oom...");
// 为快速发生oom，设置堆大小; VM args: -Xms20m -Xmx20m
//        new Thread(() -> {
//            List<OOMObject> list = new ArrayList<>();
        while (true) {
            list.add(new OOMObject());
        }
//        }).start();

//        while (true) {
//            System.out.println(Thread.currentThread().getName() + " continuing...");
//            Thread.sleep(1000L);
//        }
//        return Thread.currentThread().getName() + " oom...";
    }


    @GetMapping("/hello")
    public String hello() {
        StopWatch stopWatch = new StopWatch();
        String apiURL = "http://127.0.0.1:8081/api/hello";
        stopWatch.start();
        ResponseEntity<String> forEntity = restTemplate.getForEntity(apiURL, String.class);
        stopWatch.stop();
        System.out.println("Thread:" + Thread.currentThread().getName() + ",cost:" + stopWatch.getLastTaskTimeMillis());

        if (200 == forEntity.getStatusCodeValue()) {
            return forEntity.getBody();
        } else {
            return "error with code:" + forEntity.getStatusCodeValue();
        }

    }


    @GetMapping("/sayhello")
    public String sayhello() {
        return Thread.currentThread().getName() + " sayhello...v4.0.1";
    }


    @GetMapping("/sayhello2")
    public void sayhello2() {
        while (true) {
            System.out.println("HelloController.sayhello2");
        }
    }


    //------------------------------------easyexcel-----------------


    @Autowired
    private Validator validator;
    //        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file) throws IOException {
        UserDataListener readListener = new UserDataListener();
        EasyExcel.read(file.getInputStream(), UserData.class, readListener).sheet().sheetName("Sheet1").headRowNumber(1).doRead();
        save(readListener);
        Map<Integer, String> errorMap = readListener.getErrorMap();
        //取errorMap的values
        return Result.builder().success(true).data(errorMap.values())
                .build();
    }

    void save(UserDataListener readListener) {
        List<UserData> validUserData = readListener.getList();
        Map<Integer, String> errorMap = readListener.getErrorMap();
        //根据username分组
        Map<String, List<UserData>> userDataMap = validUserData.stream().collect(Collectors.groupingBy(UserData::getCode));

        userDataMap.forEach((k, v) -> {

                }
        );

        userDataMap.forEach((k, v) -> {
            //如果code存在，则添加对应的错误信息到errorMap
            if (existsData(v.get(0))) {
                //添加v里面的所有行到errorMap
                v.forEach(userData -> errorMap.put(userData.getRowIndex(), String.format("第%s行，数据已存在", userData.getRowIndex())));
                // errorMap.put(v.get(0).getRowIndex(), String.format("第%s行，数据已存在", v.get(0).getRowIndex()));
            } else {
                System.out.println("保存到数据库");
            }
        });


        // save to database
        for (UserData userData : validUserData) {
            if (!existsData(userData)) {
                System.out.println("保存到数据库");
            } else {
                System.out.println("数据已存在");
                errorMap.put(userData.getRowIndex(), String.format("第%s行，数据已存在", userData.getRowIndex()));
            }
        }
    }

    boolean existsData(UserData userData) {
        return true;
    }
}
